package cn.tpshion.vm.handler.task;

import cn.tpshion.vm.common.constant.BaseConstant;
import cn.tpshion.vm.common.constant.MsgType;
import cn.tpshion.vm.common.constant.NodeType;
import cn.tpshion.vm.common.utils.AssertUtil;
import cn.tpshion.vm.domain.support.K8sData;
import cn.tpshion.vm.domain.support.MsgData;
import cn.tpshion.vm.domain.support.NodeContext;
import cn.tpshion.vm.handler.KubectlHandler;
import cn.tpshion.vm.handler.task.support.AbstractNodeHandler;
import io.kubernetes.client.extended.kubectl.Kubectl;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.models.VersionInfo;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.credentials.ClientCertificateAuthentication;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Base64;

@Slf4j
@Component
public class K8sHandler extends AbstractNodeHandler<K8sData> {

    @Resource
    private KubectlHandler kubectlHandler;

    @Override
    public NodeType getNodeType() {
        return NodeType.K8S;
    }

    @Override
    protected void handleNode(NodeContext context) throws Exception {
        K8sData data = getData(context);
        ClientCertificateAuthentication authentication = new ClientCertificateAuthentication(
                Base64.getDecoder().decode(data.getClientCertificateData()),
                Base64.getDecoder().decode(data.getClientKeyData())
        );

        ApiClient client = new ClientBuilder()
                .setBasePath(data.getApiServer())
                .setAuthentication(authentication)
                .setVerifyingSsl(false)
                .build();

        String workspace = StringUtils.isBlank(data.getWorkDir()) ?
                context.getWorkspace() : context.getWorkspace() + File.separator + data.getWorkDir();

        VersionInfo versionInfo = Kubectl.version().apiClient(client).execute();
        log.info("K8sHandler VersionInfo:{}", versionInfo);
        sseHandle.sendMessage(context, MsgData.of(MsgType.INFO, "K8sHandler VersionInfo:" + versionInfo.toString()));

        String yamlFile = getYamlFile(workspace, data);
        log.info("K8sHandler yamlFile:{}", yamlFile);
        sseHandle.sendMessage(context, MsgData.of(MsgType.INFO, "K8sHandler yamlFile:" + yamlFile));
        kubectlHandler.handleFile(yamlFile, client);
    }

    private String getYamlFile(String workspace, K8sData data){
        String yamlFile = data.getFilePath();
        AssertUtil.isBlank(yamlFile, "部署文件不能为空");
        return yamlFile.contains(BaseConstant.ENV_WORKSPACE) ?
                yamlFile.replaceAll(BaseConstant.ENV_WORKSPACE, workspace) : workspace + "/" + yamlFile;
    }
}
